// @Author : zaniu(zzaniu@126.com)
// @Time   : 2021/9/7 22:14
// @Desc   :
//
//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
// =====`-.____`-.___\_____/___.-`____.-'=====
//                   `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           佛祖保佑       永无BUG
//
package main

import (
	"distributedTransaction/utils"
	"distributedTransaction/utils/nacos"
	"encoding/json"
	"fmt"
	"time"
	"unsafe"
)

type ServerConfig struct {
	UserServerName      string `json:"userServerName"`
	OrderServerName     string `json:"orderServerName"`
	InventoryServerName string `json:"inventoryServerName"`
}

func publish() {
	config := utils.GlobalConfig{
		SqlPort: 3306, SqlDbName: "test", SqlUserName: "better", SqlUserPwd: "!@#Admin123",
		RocketMQHost: "120.236.12.126", RocketMQPort: 9876, Topic: "TopicGmb", SqlHost: "129.204.241.31",
	}
	content, err := json.Marshal(config)
	if err != nil {
		panic(fmt.Sprintf("json.Marshal error, err = %s", err.Error()))
	}
	ok, err := nacos.PublishConfig("test-data", "test-group", *(*string)(unsafe.Pointer(&content)))
	if err != nil {
		panic(fmt.Sprintf("nacos.PublishConfig, err = %s", err.Error()))
	}
	if ok {
		fmt.Println("发布成功")
	} else {
		fmt.Println("发布失败")
	}
}

func getConfig() {
	config := utils.GlobalConfig{}
	configStr, err := nacos.GetConfig("test-data", "test-group")
	if err != nil {
		panic(fmt.Sprintf("nacos.GetConfig error, err = %s", err.Error()))
	}
	err = json.Unmarshal(([]byte)(configStr), &config)
	if err != nil {
		panic(fmt.Sprintf("json.Unmarshal error, err = %s", err.Error()))
	}
	fmt.Println("config = ", config)
}

func ListenConfig(dataId, group string, config **utils.GlobalConfig) error {
	return nacos.ListenConfig(dataId, group, config)
}

func main() {
	configPtr := &utils.GlobalConfig{}
	// var lock sync.RWMutex
	// ListenConfig("test-data", "test-group", &config, &lock)
	ListenConfig("test-data", "test-group", &configPtr)
	time.Sleep(time.Millisecond * 100)
	for i := 0; i < 1000000; i++ {
		time.Sleep(time.Millisecond)
		if configPtr.RocketMQHost != "120.236.12.126" {
			fmt.Println("config.rocketMQHost = ", configPtr.RocketMQHost)
			break
		}
	}
	time.Sleep(time.Second * 60 * 5)
}
